<template>
  <!-- 只保留一组上传区和播放区 -->
  <div style="display: flex; flex-direction: row;">
    <!-- 视频上传区 -->
    <div class="card upload-section" style="width: 28%;height: 500px; display: inline-block;margin: 10px;margin-right: 5px;">
      <h3><i class="fas fa-upload"></i> 视频上传</h3>
      <div v-if="!originalVideoUrl" class="upload-wrapper"> 
        <input type="file" @change="handleFileChange" 
               accept="video/*" hidden id="fileInput">
        <label for="fileInput" class="upload-label">
          <i class="fas fa-cloud-upload-alt fa-3x"></i>
          <p>点击选择视频文件或拖拽到此区域</p>
        </label>
        <progress v-if="uploadProgress > 0" :value="uploadProgress" max="100"></progress>
        <div v-if="isUploading" class="loading-overlay">
          <i class="fas fa-spinner fa-2x"></i>
          上传中，请稍候...
        </div>
      </div>
      <div v-else class="upload-section" style="width: 100%;height: 50px; display: inline-block;"> 
        <video class="video-player" controls :src="originalVideoUrl" v-if="originalVideoUrl"></video>
        <button @click="returnUpoload" class="upload-btn" style="width: 45%;float: left;margin-right: 5px;">
          <i class="fas fa-upload"></i> 重新上传
        </button>
        <button  
          @click="analyzeVideo" 
          style="width: 45%;float: left;margin-left: 5px;">
          <i class="fas fa-search"></i> 分析视频
        </button>
      </div> 
      <div v-if="isAnalyzing" style="margin-top: 20px;">
        <i class="fas fa-spinner fa-spin"></i> 正在分析，请稍候...
      </div>
    </div>

    <!-- 视频播放区 -->
    <div class="card player-section" style="width: 69%; height: 500px; display: inline-block; margin: 10px 10px 10px 5px;">
      <h3><i class="fas fa-video"></i> 视频播放</h3>
      <div v-if="analyzedVideoUrl">
        <video class="video-player" controls :src="analyzedVideoUrl" style="width: 100%; height: 400px;"></video>
      </div>
      <div v-else class="video-placeholder" style="flex">
        <i class="fas fa-film fa-3x"></i>
        <p>请先上传并分析视频文件</p>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'VideoUploader',
  props: {
    analyzedVideoUrl: {
      type: String,
      default: ''
    },
    setAnalyzedVideoUrl: {
      type: Function,
      default: () => {}
    }
  },
  data() {
    return {
      // 不要再写 analyzedVideoUrl: ''
      uploadProgress: 0,
      isUploading: false,
      originalVideoUrl: '',
      filename: '',
      isAnalyzing: false,
      analyzeResult: null,
      account: localStorage.getItem('account') || ''
    }
  },
  mounted() {
    const analyzed = localStorage.getItem('analyzedVideoUrl');
    const original = localStorage.getItem('originalVideoUrl');
    const fname = localStorage.getItem('currentAnalyzedVideo');
    if (analyzed && original && fname) {
      if (typeof this.setAnalyzedVideoUrl === 'function') {
        this.setAnalyzedVideoUrl(analyzed);
      }
      this.originalVideoUrl = original;
      this.filename = fname;
    } else {
      this.setAnalyzedVideoUrl('');
      this.originalVideoUrl = '';
      this.filename = '';
    }
    const account = localStorage.getItem('account');
    if (!account) return; // 没有登录不请求
    axios.get('/api/get-results/' + account)
      .then(() => {
        // 处理结果
      });
  },
  methods: {
    returnUpoload() {
      this.setAnalyzedVideoUrl('');
      this.originalVideoUrl = '';
      this.filename = '';
      this.uploadProgress = 0; 
      localStorage.removeItem('currentAnalyzedVideo');
      localStorage.removeItem('originalVideoUrl');
      localStorage.removeItem('analyzedVideoUrl');
    },
    handleFileChange(e) {
      const file = e.target.files[0];
      if (!file) return;

      if (!this.account) {
        alert('请先登录或刷新页面获取用户信息');
        return;
      }

      this.isUploading = true;
      this.uploadProgress = 0;

      const formData = new FormData();
      formData.append('file', file);
      axios.post('/api/upload-video', formData, {
        headers: { 'Content-Type': 'multipart/form-data' }
      })
      .then(response => {
        this.isUploading = false;
        this.uploadProgress = 100;
        this.originalVideoUrl = response.data.videoUrl;
        this.filename = response.data.video_name || response.data.filename;
        localStorage.setItem('originalVideoUrl', this.originalVideoUrl);
        localStorage.setItem('currentAnalyzedVideo', this.filename);
      })
      .catch(error => {
        this.isUploading = false;
        this.uploadProgress = 0;
        alert('上传失败: ' + (error.response?.data?.message || error.message));
      });
    },
    analyzeVideo() {
      if (!this.filename) {
        alert('请先上传视频');
        return;
      }
      if (!this.account) {
        alert('请先登录或刷新页面获取用户信息');
        return;
      }
      this.isAnalyzing = true;
      axios.post('/api/analyze-video', {
        filename: this.filename,
        account: localStorage.getItem('account')
      })
        .then(res => {
          this.isAnalyzing = false;
          this.analyzeResult = res.data.results;
          alert('分析成功');
          localStorage.setItem('currentAnalyzedVideo', this.filename)
          localStorage.setItem('account', this.account)
          const combined = res.data.results.find(item =>
            item.file_path && item.file_path.toLowerCase().includes('combined1.mp4')
          );
          if (combined && typeof this.setAnalyzedVideoUrl === 'function') {
            let videoUrl = combined.file_path;
            if (!/^https?:\/\//.test(videoUrl) && !videoUrl.startsWith('/')) {
              videoUrl = '/' + videoUrl;
            }
            console.log('分析后视频地址:', videoUrl);
            this.setAnalyzedVideoUrl(videoUrl);
            localStorage.setItem('analyzedVideoUrl', videoUrl);
          }
        })
        .catch(err => {
          this.isAnalyzing = false;
          alert('分析失败: ' + (err.response?.data?.message || err.message));
        });
    },
    onLoginSuccess(payload) {
      this.isLoggedIn = true;
      this.account = payload.account;
      this.userType = payload.userType;
      this.setAnalyzedVideoUrl('');
      localStorage.removeItem('currentAnalyzedVideo');
      localStorage.removeItem('originalVideoUrl');
      localStorage.removeItem('analyzedVideoUrl');
      this.$router.push('/home');
    },
  }
}
</script>